<?php
namespace app\forum\model;
use app\base\model\BaseModel;
/**
 * 用户组操作
 */
class UserGroupModel extends BaseModel {
    //完成
    protected $_auto = array (
         array('status','intval',3,'function'),
         array('name','htmlspecialchars',3,'function'),
     );
    //验证
    protected $_validate = array(
        array('name','1,20', '用户组名称只能为1~20个字符', 0 ,'length',3),
    );

    /**
     * 获取列表
     * @return array 列表
     */
    public function loadList($where = array(), $order = 'special ASC, integral_limit ASC, group_id ASC'){
        return $this->where($where)->order($order)->select();
    }

    /**
     * 获取信息
     * @param int $groupId ID
     * @return array 信息
     */
    public function getInfo($groupId = 1)
    {
        $map = array();
        $map['group_id'] = $groupId;
        return $this->where($map)->find();
    }

    /**
     * 更新信息
     * @param string $type 更新类型
     * @return bool 更新状态
     */
    public function saveData($type = 'add'){
        $data = $this->create();
        if(!$data){
            return false;
        }
        if($type == 'add'){
            return $this->add();
        }
        if($type == 'edit'){
            if(empty($data['group_id'])){
                return false;
            }
            $status = $this->save();
            if($status === false){
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 删除信息
     * @param int $groupId ID
     * @return bool 删除状态
     */
    public function delData($groupId)
    {
        if($groupId == 1){
            $this->error = '默认用户组无法删除';
            return false;
        }
        $this->beginTransaction();
        //修改所有用户为普通组
        $where = array();
        $where['group_id'] = $groupId;
        $data = array();
        $data['group_id'] = 1;
        $status = target('forum/User')->where($where)->data($data)->update();
        if($status === false){
            $this->error = target('forum/User')->getError();
            $this->rollBack();
            return false;
        }
        //删除用户组
        $map = array();
        $map['group_id'] = $groupId;
        $status = $this->where($map)->delete();
        if($status){
            $this->commit();
        }else{
            $this->rollBack();
        }
        return $status;
    }

}
